package com.rfid.project.web;

import java.text.DateFormat;
import java.util.List;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.data.domain.Page;

import biz.appframe.PageJsonBean;

import com.rfid.project.exception.CannotDelException;
import com.rfid.project.model.ProjectTask;
import com.rfid.project.service.ProcessStatus;
import com.rfid.project.service.ProjectMemberService;
import com.rfid.project.service.ProjectTaskService;
import com.rfid.project.service.ProjectTaskPersonService;
import com.rfid.project.model.Project;
import com.rfid.project.service.ProjectService;
import com.rfid.project.model.People;
import com.rfid.project.service.PeopleService;
import com.rfid.project.model.ProjectTaskType;
import com.rfid.project.service.ProjectTaskTypeService;

@Controller
public class ProjectTaskController {

	private static final Logger logger = LoggerFactory
			.getLogger(ProjectTaskController.class);

	@Autowired
	private ProjectTaskService projectTaskService;

	@Autowired
	private ProjectService projectService;

	@Autowired
	private PeopleService peopleService;

	@Autowired
	private ProjectTaskTypeService projectTaskTypeService;

	@Autowired
	private ProjectMemberService projectMemberService;

	@Autowired
	private ProjectTaskPersonService projetTaskPersonService;
	
	@RequestMapping(value = "/projectTaskmgr")
	public String projectTaskmgr(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		List<Project> projects = projectService.findAll();
		model.addAttribute("projects", projects);

		List<People> taskCreators = peopleService.findAll();
		model.addAttribute("peoples", taskCreators);

		List<ProjectTaskType> projectTaskTypes = projectTaskTypeService.findAll();
		model.addAttribute("projectTaskTypes", projectTaskTypes);
		return "projectTaskmgr";
	}

	@RequestMapping(value = "/queryProjectTask")
	public String queryProjectTask(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "projectId", defaultValue = "-1") Long projectId,
			@RequestParam(value = "taskCreatorId", defaultValue = "-1") Long taskCreatorId,
			@RequestParam(value = "taskCreateTimeBegin", defaultValue = "") Date taskCreateTimeBegin,
			@RequestParam(value = "taskCreateTimeEnd", defaultValue = "") Date taskCreateTimeEnd,
			@RequestParam(value = "planFinishDateBegin", defaultValue = "") Date planFinishDateBegin,
			@RequestParam(value = "planFinishDateEnd", defaultValue = "") Date planFinishDateEnd,
			@RequestParam(value = "actualFinishDateBegin", defaultValue = "") Date actualFinishDateBegin,
			@RequestParam(value = "actualFinishDateEnd", defaultValue = "") Date actualFinishDateEnd,
			@RequestParam(value = "taskDescription", defaultValue = "") String taskDescription,
			@RequestParam(value = "status", defaultValue = "") String status,
			@RequestParam(value = "projectTaskTypeId", defaultValue = "-1") Long projectTaskTypeId,
			@RequestParam(value = "page", defaultValue = "1") Integer pageNumber,
			@RequestParam(value = "rows", defaultValue = "10") Integer pageSize,
			@RequestParam(value = "sort", defaultValue = "") String sort,
			@RequestParam(value = "order", defaultValue = "") String order,
			Model model) {
		Page<ProjectTask> projectTasks = projectTaskService.findAll(projectId,
				taskCreatorId, taskCreateTimeBegin, taskCreateTimeEnd,
				planFinishDateBegin, planFinishDateEnd,
				actualFinishDateBegin, actualFinishDateEnd, taskDescription,
				status, projectTaskTypeId, pageNumber, pageSize, sort, order);
		JSONObject object = new JSONObject();
		object.put("total", projectTasks.getTotalElements());
		JSONArray models = new JSONArray();
		for (ProjectTask item : projectTasks) {
			JSONObject mod = new JSONObject();
			wrapData(item, mod);

			models.add(mod);
		}
		object.put("rows", models);
		PageJsonBean.printObject(response, object);
		return null;
	}
	
	@RequestMapping(value = "/findProjectTask")
	public String findProjectTask(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "-1") Long id,
			Model model) {
		ProjectTask projectTask = projectTaskService.findOne(id);
		JSONObject object = new JSONObject();
		JSONObject mod = new JSONObject();
		wrapData(projectTask, mod);
		object.put("success", true);
		object.put("data", mod);
		PageJsonBean.printObject(response, object);
		return null;
	}

	private void wrapData(ProjectTask item, JSONObject mod) {
		mod.put("id", item.getId());
		mod.put("status", ProcessStatus.processStatusName(item.getStatus()));
		mod.put("statusCode", item.getStatus());
		mod.put("taskCreateTime", com.rfid.project.util.DateUtil.dateTheDayToString(item.getTaskCreateTime()));
		mod.put("planFinishDate", com.rfid.project.util.DateUtil.dateTheDayToString(item.getPlanFinishDate()));
		mod.put("taskDescription", item.getTaskDescription());
		mod.put("actualFinishDate", com.rfid.project.util.DateUtil.dateTheDayToString(item.getActualFinishDate()));
		
		Float planWorktime = item.getPlanWorktime();
		mod.put("planWorktime", planWorktime == null?0:planWorktime);
		
		Float ctualWorktime = item.getActualWorktime();
		mod.put("actualWorktime", ctualWorktime == null?0:ctualWorktime);
		mod.put("projectId", item.getProject().getId());
		mod.put("projectName", item.getProject().getName());
		mod.put("taskCreatorId", item.getTaskCreator().getId());
		mod.put("taskCreatorName", item.getTaskCreator().getName());
		mod.put("projectTaskTypeId", item.getProjectTaskType().getId());
		mod.put("projectTaskTypeName", item.getProjectTaskType().getName());
	}

	@RequestMapping(value = "/editProjectTask", method = RequestMethod.POST)
	public String editProjectTask(HttpServletRequest request,
			HttpServletResponse response, @Valid ProjectTask projectTask,
			Model model, RedirectAttributes redirectAttributes) {
		projectTaskService.saveProjectTask(projectTask);

		JSONObject result = new JSONObject();
		result.put("success", true);
		PageJsonBean.printObject(response, result);
		return null;
	}

	@RequestMapping(value = "/delProjectTask")
	public String delProjectTask(
			HttpServletRequest request, 
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "") Long id) {
		JSONObject result = new JSONObject();
		boolean flag = true;
		try {
			this.projectTaskService.deleteProjectTask(id);
		} catch (CannotDelException e) {
			flag = false;
			result.put("msg",e.getMessage());
		}
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}
	
	@RequestMapping(value = "/applyDelayProjectTask")
	public String applyDelayProjectTask(HttpServletRequest request,
			HttpServletResponse response, @Valid ProjectTask projectTask,
			Model model, RedirectAttributes redirectAttributes) {
		projectTaskService.applyDelayProjectTask(projectTask);
		JSONObject result = new JSONObject();
		result.put("success", true);
		PageJsonBean.printObject(response, result);
		return null;
	}
	
	@RequestMapping(value = "/applyFinishProjectTask")
	public String applyFinishProjectTask(HttpServletRequest request,
			HttpServletResponse response, @Valid ProjectTask projectTask,
			Model model, RedirectAttributes redirectAttributes) {
		projectTaskService.applyFinishProjectTask(projectTask);
		JSONObject result = new JSONObject();
		result.put("success", true);
		PageJsonBean.printObject(response, result);
		return null;
	}
	
	@InitBinder
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		DateFormat dateFormat = com.rfid.project.util.DateUtil.getFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(
				dateFormat, true));
	}

}
